package com.yiren.manager.ctrl.cost;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yiren.core.exception.MyException;
import com.yiren.core.exception.SwallowException;
import com.yiren.core.repository.utils.QueryResult;
import com.yiren.core.utils.HTTPResult;
import com.yiren.core.utils.JsonMapperTool;
import com.yiren.core.utils.StringUtil;
import com.yiren.core.utils.UUIDGenerator;
import com.yiren.entity.YrElder;
import com.yiren.entity.YrElderPayRecord;
import com.yiren.entity.YrElderPayReturnApply;
import com.yiren.entity.YrElderWallet;
import com.yiren.entity.YrStaffInfo;
import com.yiren.entity.YrUserVipCard;
import com.yiren.entity.YrUserVipCardRecord;
import com.yiren.manager.ctrl.elder.YrElderBaseController;
import com.yiren.manager.form.cost.ApplyModuleForm;
import com.yiren.manager.form.cost.YrElderPayReturnApplyForm;
import com.yiren.manager.service.iface.cost.YrElderPayRecordService;
import com.yiren.manager.service.iface.cost.YrElderPayReturnApplyService;
import com.yiren.manager.service.iface.department.YrStaffInfoService;
import com.yiren.manager.service.iface.elder.YrElderService;
import com.yiren.manager.service.iface.elder.YrElderWalletService;
import com.yiren.manager.service.iface.elder.YrWalletReturnService;
import com.yiren.manager.service.iface.vip.YrUserVipCardRecordService;
import com.yiren.manager.service.iface.vip.YrUserVipCardService;
import com.yiren.manager.utils.ObjectUtils;

@RequestMapping("elderPayReturnApply")
@Controller
public class YrElderPayReturnApplyController
		extends YrElderBaseController<YrElderPayReturnApplyForm, YrElderPayReturnApply> {

	@Autowired
	private YrElderPayReturnApplyService selfService;

	@Autowired
	private YrElderPayRecordService elderPayRecordService;

	@Autowired
	private YrStaffInfoService staffInfoService;

	@Autowired
	private YrElderWalletService elderWalletService;

	@Autowired
	private YrWalletReturnService walletReturnService;

	@Autowired
	private YrElderService elderService;
	
	@Autowired
	private YrUserVipCardService userVipCardService;
	
	@Autowired
	private YrUserVipCardRecordService userVipCardRecordService;
	/**
	 * 退费申请
	 * 
	 * @param data
	 * @return
	 * @throws SwallowException
	 * @throws MyException
	 */
	@RequestMapping("elderPayReturnApply")
	@ResponseBody
	public HTTPResult<YrElderPayReturnApplyForm> apply(String data) throws SwallowException, MyException {
		HTTPResult<YrElderPayReturnApplyForm> result = new HTTPResult<YrElderPayReturnApplyForm>();
		JsonMapperTool tool = new JsonMapperTool(data);

		ApplyModuleForm form = tool.mapper("applyModuleForm", ApplyModuleForm.class);

		Date now = new Date();
		for (String payRecordId : form.getPayRecordIds()) {
			YrElderPayRecord elderPayRecord = elderPayRecordService.findOne(payRecordId);
			if (null == elderPayRecord) {
				continue;
			}
			if(form.getMoney()-elderPayRecord.getPayMoney()>0){
				throwExp("退费的金额不能大于缴费金额");
			}
			YrElderPayReturnApply elderPayReturnApply = new YrElderPayReturnApply();
			elderPayReturnApply.setElderPayReturnApplyId(UUIDGenerator.getUUID());
			elderPayReturnApply.setCostDesc(elderPayRecord.getCostDesc());
			elderPayReturnApply.setElderId(elderPayRecord.getElderId());
			elderPayReturnApply.setElderName(elderPayRecord.getElderName());
			elderPayReturnApply.setElderCardId(elderPayRecord.getElderCardId());
			elderPayReturnApply.setReturnMoney(form.getMoney());
			elderPayReturnApply.setPayMoney(elderPayRecord.getPayMoney());
			elderPayReturnApply.setPayDate(elderPayRecord.getPayDate());
			elderPayReturnApply.setCreateTime(now);
			elderPayReturnApply.setCreateId(form.getCreateId());
			elderPayReturnApply.setElderPayRecordId(elderPayRecord.getElderPayRecordId());
			elderPayReturnApply.setPayStatus(elderPayRecord.getPayStatus());
			elderPayReturnApply.setPayWay(elderPayRecord.getPayWay());
			elderPayReturnApply.setReturnReason(form.getReasonDesc());
			elderPayReturnApply.setSubjectRoomId(elderPayRecord.getSubjectRoomId());
			elderPayReturnApply.setApplyDate(now);
			elderPayReturnApply.setResultStatus(0);
			elderPayReturnApply.setBeHospitalId(elderPayRecord.getBeHospitalId());
			
			selfService.save(elderPayReturnApply);
		}

		return result;
	}

	/**
	 * 获取未审批的
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("findOnaylanmam")
	@ResponseBody
	public HTTPResult<YrElderPayReturnApplyForm> findOnaylanmam() throws Exception {
		HTTPResult<YrElderPayReturnApplyForm> result = new HTTPResult<YrElderPayReturnApplyForm>();
		String sqlWhere = "result_status=0";
		
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("applyDate", "ASC");
		QueryResult<YrElderPayReturnApply> qr = selfService.find(YrElderPayReturnApply.class, sqlWhere,
				new Object[] {},map);
		List<YrElderPayReturnApplyForm> formList = new ArrayList<YrElderPayReturnApplyForm>();
		for (YrElderPayReturnApply entity : qr.getResultList()) {
			YrElderPayReturnApplyForm form = toForm(entity);
			if (null != form.getCreateId()) {
				YrStaffInfo staffInfo = staffInfoService.findOne(form.getCreateId());
				if (null != staffInfo) {
					form.setHandler(staffInfo.getName());
				}
			}
			formList.add(form);
		}
		result.setData(formList);

		return result;
	}

	/**
	 * 批量操作审批意见
	 * 
	 * @param ids
	 * @param resultStatus
	 * @return
	 * @throws MyException
	 */
	@RequestMapping("updateResultBatch")
	@ResponseBody
	public HTTPResult<YrElderPayReturnApplyForm> updateResultBatch(String ids, Integer resultStatus) throws MyException {
		HTTPResult<YrElderPayReturnApplyForm> result = new HTTPResult<YrElderPayReturnApplyForm>();

		String sqlWhere = "elder_id=?1";
		String[] idArr = ids.split(",");
		for (String id : idArr) {
			if(StringUtil.isNull(id)){
				continue;
			}
			YrElderPayReturnApply entity = selfService.findOne(id);
			YrElder elder = elderService.findOne(entity.getElderId());
			if (null != entity && null!=elder) {
				if(entity.getResultStatus()==1||entity.getResultStatus()==2){
					throwExp("老者"+entity.getElderName()+"的退费申请已经审批，请勿重复审批");
				}
				entity.setResultStatus(resultStatus);
				if (resultStatus == 1) {//如果同意退费
					YrElderPayRecord elderPayRecord = elderPayRecordService.findOne(entity.getElderPayRecordId());
					if (null == elderPayRecord) {
						throwExp("查询不到相关缴费记录");
					}
					QueryResult<YrElderWallet> qrElderWallet = elderWalletService.find(YrElderWallet.class, sqlWhere,
							new Object[] { elderPayRecord.getElderId() });
					if (qrElderWallet.getTotalRecord() == 0) {
						throwExp("老者"+elderPayRecord.getElderName()+"尚未有钱包，折扣金额无法返还");
					}

					elderPayRecord.setPayStatus(3);
					elderPayRecord.setReturnMoney((elderPayRecord.getReturnMoney()==null?0:elderPayRecord.getReturnMoney())+
						entity.getReturnMoney());
					elderPayRecord.setReturnTime(new Date());
					elderPayRecordService.save(elderPayRecord);
					
					//新增一条退费的缴费记录
					YrElderPayRecord returnPayRecord = costElderPayRecord(elderPayRecord.getBeHospitalId(),
							elderPayRecord.getCostDesc(), elder, elderPayRecord.getCostType(), elderPayRecord.getElderPayRecordId(), 
							0-entity.getReturnMoney(), 
								2, 2, entity.getUpdateId(),elderPayRecord.getQuantity()); 
					
					elderPayRecordService.save(returnPayRecord);
					entity.setReturnTime(new Date());
					
					YrElderWallet elderWallet = qrElderWallet.getResultList().get(0);
					elderWallet.setWalletBalance(elderWallet.getWalletBalance() + entity.getReturnMoney());

//					YrWalletReturn walletReturn = new YrWalletReturn();
//					walletReturn.setElderId(entity.getElderId());
//					walletReturn.setRelationId(entity.getElderPayReturnApplyId());
//					walletReturn.setReturnMoney(entity.getReturnMoney());
//					walletReturn.setReturnTime(new Date());
//					walletReturn.setWalletReturnId(UUIDGenerator.getUUID());
//					walletReturn.setCreateTime(new Date());
//					walletReturn.setSource(2);//设置退款来源为缴费退款
//					walletReturn.setBeHospitalId(elderPayRecord.getBeHospitalId());
					
//					walletReturnService.save(walletReturn);
					
					elderWalletService.save(elderWallet);
				}
				selfService.save(entity);
			}
		}
		return result;
	}

	/**
	 * 操作审批意见
	 * 
	 * @param ids
	 * @param resultStatus
	 * @return
	 * @throws MyException
	 */
	@RequestMapping("updateResult")
	@ResponseBody
	public HTTPResult<YrElderPayReturnApplyForm> updateResult(String id, Integer resultStatus) throws MyException {
		HTTPResult<YrElderPayReturnApplyForm> result = new HTTPResult<YrElderPayReturnApplyForm>();
		YrElderPayReturnApply entity = selfService.findOne(id);

		if (null == entity) {
			throwExp("查询不到相关的退费申请记录");
		}
		
		if(entity.getResultStatus()==1||entity.getResultStatus()==2){
			throwExp("老者"+entity.getElderName()+"的退费申请已经审批，请勿重复审批");
		}
		String sqlWhere = "elder_id=?1";
		entity.setResultStatus(resultStatus);
		if (resultStatus == 1) {//如果同意退费
			YrElderPayRecord elderPayRecord = elderPayRecordService.findOne(entity.getElderPayRecordId());
			if (null == elderPayRecord) {
				throwExp("查询不到相关缴费记录");
			}

			YrElder elder = elderService.findOne(entity.getElderId());
			if(null==elder){
				throwExp("查询不到老者相关信息");
			}
			QueryResult<YrElderWallet> qrElderWallet = elderWalletService.find(YrElderWallet.class, sqlWhere,
					new Object[] { elderPayRecord.getElderId() });
			if (qrElderWallet.getTotalRecord() == 0) {
				throwExp("该老者尚未有钱包，折扣金额无法返还");
			}
			
			elderPayRecord.setPayStatus(3);
			elderPayRecord.setReturnMoney((elderPayRecord.getReturnMoney()==null?0:elderPayRecord.getReturnMoney())+
					entity.getReturnMoney());
			elderPayRecord.setReturnTime(new Date());
		
			//新增一条退费的缴费记录
			YrElderPayRecord returnPayRecord = costElderPayRecord(elderPayRecord.getBeHospitalId(),
					elderPayRecord.getCostDesc(), elder, elderPayRecord.getCostType(), elderPayRecord.getElderPayRecordId(), 
					0-entity.getReturnMoney(), 
						2, 2, entity.getUpdateId(),elderPayRecord.getQuantity()); 
			entity.setReturnTime(new Date());
			if(elderPayRecord.getPayWay()==3){//如果是VIP卡退费 则退回vip卡
				YrUserVipCard userVipCard = userVipCardService.findOne(elderPayRecord.getRelationId());
				if(userVipCard==null){
					throwExp("查询不到缴费时绑定的vip卡信息，请检查是否该卡已被删除");
				}
				//更新用户vip信息
				userVipCard.setBuckleNumber(userVipCard.getBuckleNumber() + 1);
				userVipCard.setDeductNumber(userVipCard.getDeductNumber() - 1);
				
				userVipCard.setUseStatus(userVipCard.getBuckleNumber() == 0 ? 2 : 1);
				userVipCard.setSurplusMonths(Float.valueOf(userVipCard.getBuckleNumber()) / 30);
				userVipCard.setUpdateTime(new Date());
				userVipCardService.save(userVipCard);
				
				//更新用户vip卡使用记录
				sqlWhere = "elder_id=?1 AND user_vip_card_id=?2";
				YrUserVipCardRecord userVipCardRecord = null;
				QueryResult<YrUserVipCardRecord> qrUserVipCardRecord = userVipCardRecordService.find(YrUserVipCardRecord.class,
						sqlWhere, new Object[] { elder.getElderId(),userVipCard.getUserVipCardId()});
				if (qrUserVipCardRecord.getTotalRecord() > 0) {// 已存在记录
					userVipCardRecord = qrUserVipCardRecord.getResultList().get(0);
					userVipCardRecord.setPayNum(userVipCardRecord.getPayNum() - 1);
					userVipCardRecord.setUseMonthNum(userVipCard.getConsumptionType() == 1 ? userVipCardRecord.getPayNum() / 30
							: userVipCardRecord.getPayNum());
					userVipCardRecord.setUpdateTime(new Date());
					userVipCardRecordService.save(userVipCardRecord);
				}
			}else{
				YrElderWallet elderWallet = qrElderWallet.getResultList().get(0);
				elderWallet.setWalletBalance(elderWallet.getWalletBalance() + entity.getReturnMoney());
				elderWalletService.save(elderWallet);
			}
			elderPayRecordService.save(elderPayRecord);
			elderPayRecordService.save(returnPayRecord);
//			YrWalletReturn walletReturn = new YrWalletReturn();
//			walletReturn.setElderId(entity.getElderId());
//			walletReturn.setRelationId(entity.getElderPayReturnApplyId());
//			walletReturn.setReturnMoney(entity.getReturnMoney());
//			walletReturn.setReturnTime(new Date());
//			walletReturn.setWalletReturnId(UUIDGenerator.getUUID());
//			walletReturn.setCreateTime(new Date());
//			walletReturn.setSource(2);//设置退款来源为缴费退款
//			walletReturn.setBeHospitalId(elderPayRecord.getBeHospitalId());
			
//			walletReturnService.save(walletReturn);
		}
		selfService.save(entity);
		return result;
	}

	/**
	 * 查询已经审批的
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("findExamined")
	@ResponseBody
	public HTTPResult<YrElderPayReturnApplyForm> findExamined() throws Exception {
		HTTPResult<YrElderPayReturnApplyForm> result = new HTTPResult<YrElderPayReturnApplyForm>();

		String sqlWhere = "result_status=1 OR result_status=2";
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("returnTime", "DESC");
		QueryResult<YrElderPayReturnApply> qr = selfService.find(YrElderPayReturnApply.class, sqlWhere,
				new Object[] {});
		List<YrElderPayReturnApplyForm> formList = new ArrayList<YrElderPayReturnApplyForm>();
		for (YrElderPayReturnApply entity : qr.getResultList()) {
			YrElderPayReturnApplyForm form = toForm(entity);
			if (null != entity.getCreateId()) {
				YrStaffInfo hander = staffInfoService.findOne(entity.getCreateId());
				form.setHandler(hander.getName());
			}
			if (null != entity.getApproveId()) {
				YrStaffInfo approve = staffInfoService.findOne(entity.getApproveId());
				form.setApprover(approve.getName());
			}
			formList.add(form);
		}

		result.setData(formList);
		return result;
	}

	/**
	 * 根据
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("findBySearchVal")
	@ResponseBody
	public HTTPResult<YrElderPayReturnApplyForm> findBySearchVal(String searchVal) throws Exception {
		HTTPResult<YrElderPayReturnApplyForm> result = new HTTPResult<YrElderPayReturnApplyForm>();

		String sqlWhere = "elder_name=?1 OR elder_card_id=?2";
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("applyDate", "ASC");
		QueryResult<YrElderPayReturnApply> qr = selfService.find(YrElderPayReturnApply.class, sqlWhere,
				new Object[] { searchVal, searchVal },map);
		List<YrElderPayReturnApplyForm> formList = new ArrayList<YrElderPayReturnApplyForm>();
		for (YrElderPayReturnApply entity : qr.getResultList()) {
			YrElderPayReturnApplyForm form = toForm(entity);
			if (null != entity.getCreateId()) {
				YrStaffInfo hander = staffInfoService.findOne(entity.getCreateId());
				form.setHandler(hander.getName());
			}
			if (null != entity.getApproveId()) {
				YrStaffInfo approve = staffInfoService.findOne(entity.getApproveId());
				form.setApprover(approve.getName());
			}
			formList.add(form);
		}

		result.setData(formList);
		return result;
	}

	@Override
	public YrElderPayReturnApplyForm toForm(YrElderPayReturnApply e) throws Exception {
		YrElderPayReturnApplyForm form = ObjectUtils.objectToObject(e, YrElderPayReturnApplyForm.class);
		return form;
	}

	@Override
	public YrElderPayReturnApply toEntity(YrElderPayReturnApplyForm f) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
